package com.zoe.onelink.logging.trace.zipkin.util;

import brave.internal.Platform;
import brave.internal.codec.HexCodec;
import com.zoe.onelink.common.constant.TraceSpanConstant;
import com.zoe.onelink.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import zipkin2.Span;
import zipkin2.codec.SpanBytesDecoder;

import java.util.List;
import java.util.Map;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-10-10
 */
@Slf4j(topic = "onelink.SpanLogReporter")
public class ZipkinSpanUtil {


    public static void logSpan(byte[] body, SpanBytesDecoder decoder) {
        if (body == null || body.length == 0) {
            return;
        }
        List<Span> spans;
        if (decoder == SpanBytesDecoder.JSON_V2 || decoder == SpanBytesDecoder.JSON_V1) {
            // ASCII编码 '[' = 91
            spans = body[0] == 91 ? decoder.decodeList(body) : List.of(decoder.decodeOne(body));
        } else if (decoder == SpanBytesDecoder.THRIFT) {
            spans = body[0] == 12 ? decoder.decodeList(body) : List.of(decoder.decodeOne(body));
        } else {
            spans = decoder.decodeList(body);
        }
        for (Span span : spans) {
            ZipkinSpanUtil.logSpan(span);
        }
    }
    public static void logSpan(Span span) {
        if (span == null) {
            return;
        }
        Map<String, String> tagMap = span.tags();
        boolean hasError = tagMap != null && StrUtil.isNotBlank(tagMap.get(TraceSpanConstant.EXCEPTION_CLASS_NAME));
        if (hasError) {
            Map<String, String> tags = span.tags();
            if (tags != null && TraceSpanConstant.ExGroup.BIZ.equals(tags.get(TraceSpanConstant.EXCEPTION_GROUP))) {
                log.warn(span.toString());
            } else {
                log.error(span.toString());
            }
        } else if (log.isInfoEnabled()) {
            log.info(span.toString());
        }
    }

    /**
     * 生成链路ID
     */
    public static String generateTraceId() {
        return HexCodec.toLowerHex(Platform.get().randomLong());
    }


}
